#include "ttMsgMap.h"
#include "autoLock.h"

ttMsgMap::_msgloopvar::_msg::_msg()
{
	memset(buf, 0, sizeof(buf));
}

ttMsgMap::_msgloopvar::~_msgloopvar()
{}

int
ttMsgMap::_msgloopvar::DrawMsg(HDC hdc)
{
	autoLock lock(ttMsgMap::Get()->m_msglpvar.m_csMsgList);
	int size = ttMsgMap::Get()->m_msglpvar.m_msglist.size();
	static int beginpos;
	static int msgSize;
	static bool bfirsttime = true;
	static ttMsgMap::_msgloopvar::MSGLIST::iterator citer;
	if (bfirsttime && ttMsgMap::Get()->m_msglpvar.m_msglist.size() > 0){
		citer = ttMsgMap::Get()->m_msglpvar.m_msglist.begin();
		beginpos = 0;
		size = ttMsgMap::Get()->m_msglpvar.m_msglist.size();
		bfirsttime = false;
	}

	if (!bfirsttime){

		if (beginpos < size - 10){
			for (int i = 0; i < size - 10 - beginpos; ++ i){
				++ citer;
			}
			beginpos = size - 10;
		}

		static int cntNoChange;
		if (msgSize < ttMsgMap::Get()->m_msglpvar.m_msglist.size()){
			if (cntNoChange >= 400){
				for (int i = 0; i < msgSize - beginpos; ++ i){
					++ citer;
				}
				beginpos = msgSize;
			}
			msgSize = ttMsgMap::Get()->m_msglpvar.m_msglist.size();
			cntNoChange = 0;
		}
		else{
			++ cntNoChange;
		}
		
		if (cntNoChange < 400) {
			if (beginpos < size){
				int cnt = 0;
				WCHAR output[256];
				for (ttMsgMap::_msgloopvar::MSGLIST::iterator iter = citer; iter != ttMsgMap::Get()->m_msglpvar.m_msglist.end(); ++iter){
					memset(output, 0, sizeof(output));
					int len = wsprintf(output, L"%s", (*iter)->buf);
					TextOut(hdc, 10, 30*cnt, output, len);
					++ cnt;
				}
			}
		}
	}
	return 0;
}

ttMsgMap::ttMsgMap() : m_defFunc(NULL)
{}

ttMsgMap::~ttMsgMap()
{
	for (TTLIST::iterator iter = m_MsgMap.begin(); iter != m_MsgMap.end(); ++ iter){
		if (NULL != (*iter)){
			delete *iter;
		}
	}
}

int 
ttMsgMap::push_front(IttFunc *pFunc)
{
	m_MsgMap.push_front(pFunc);
	return 0;
}

int 
ttMsgMap::run(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	for (TTLIST::iterator iter = m_MsgMap.begin(); iter != m_MsgMap.end(); ++ iter){
		if (NULL != (*iter)){
			int ret = (*iter)->runShell(hwnd, message, wParam, lParam);
			if (0 == ret){
				return ret;			
			}
			else if (1 == ret){
				return callDefFunc(hwnd, message, wParam, lParam);
			}
		}
	}
	return callDefFunc(hwnd, message, wParam, lParam);
}

int 
ttMsgMap::setDefFunc(IttFunc *pdef)
{
	m_defFunc = pdef;
	return 0;
}

int 
ttMsgMap::callDefFunc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	if (NULL != this->m_defFunc){
		return this->m_defFunc->runShell(hwnd, message, wParam, lParam);
	}
	return 0;
}